<template>
  <div class="friendVerify autoGrow flex-column">
    <div class="friendVerifyHeader flex-row">
      <div class="subTitle">好友验证</div>
      <div>
        <el-button type="primary" size="small" @click="syncVerify">同步验证信息</el-button>
      </div>
    </div>
    <div class="verifyTabs flex-row">
      <button
        @click="changeTab(2)"
        :class="['layui-btn', 'layui-btn-xs', tab != '2' && 'layui-btn-primary'] ">
        待验证
      </button>
      <button
        @click="changeTab(1)"
        :class="['layui-btn', 'layui-btn-xs', tab != '1' && 'layui-btn-primary'] ">
        已通过
      </button>
      <button
        @click="changeTab(4)"
        :class="['layui-btn', 'layui-btn-xs', tab != '4' && 'layui-btn-primary'] ">
        已过期
      </button>
    </div>
    <div class="verifyListContainer autoGrow flex-column">
      <div class="verifyListTitle">
        <input type="checkbox" @change="toggleSelectAll" v-if="tab=='refer'">
        <span>共{{matchedList.length}}人</span>
      </div>
      <div class="verifyList autoGrow flex-column">
        <label v-for="(user, index) in matchedList" :key="index">
        <user-list-item
          class="user-list-item"
          :showBadge="false"
          :showLastMessage="false"
          :showGender="true"
          currentUserWxId=""
          :item="user">
          <template v-slot:checkbox v-if="user.type==2">
            <div>
                <!-- 之前是如果开启自动验证 就不现实复选框  v-if="!autoVerify" -->
              <input type="checkbox" :checked="selectedList.filter(u=>u.wxid==user.wxid && u.wxaccount==user.wxaccount).length>0"
              @change="toggleUserSelect(user, $event)">
            </div>
          </template>
          <template v-slot:bottomInfo>
            <div>
              {{user.wxid}}
            </div>
          </template>
          <template v-slot:attachInfo>
            <div class="flex-row attachInfoContainer">
              <span>添加好友</span>
              <div class="list-label flex-row">
                <div class="flex-row autoGrow">
                <div class="list-item-avatar">
                  <img :src="user.service.src||user.service.avatar" alt="">
                </div>
                <div class="service-item-info list-item-info flex-column">
                  <div class="serviceItemTopInfo listItemTopInfo flex-row">
                      <div class="serviceItemName listItemName textEllipsis">{{user.service.nick}}</div>
                  </div>
                  <div class="serviceItemBottomInfo list-item-bottom-info flex-row">
                    <span v-if="user.service.friendcount||user.service.friendcount==0">好友{{user.service.friendcount}}</span>
                    <span v-if="user.service.groupCount||user.service.groupCount==0">群{{user.service.groupCount}}</span>
                  </div>
                </div>
                </div>
              </div>

              <div class="requestTime">{{user.time}}</div>
            </div>
          </template>
        </user-list-item>
        </label>
      </div>
    </div>
    <button class="layui-btn layui-btn-sm acceptVerify" @click="acceptRequest">通过验证</button>
  </div>
</template>
<script>
import {mapState} from 'vuex'
import UserListItem from '@/components/userListItem';
import ServiceListItem from '@/components/serviceListItem';

export default {
  name:'friendVerify',
  data() {
    /**
     * 状态0: 未知状态，可能是企业号
      1: 已经添加为好友(界面显示"已添加")
      2: 别人请求添加我为好友，等待我的验证(界面显示"查看")
      3: 我添加别人为好友，别人回复了，等待对方的验证(界面显示"等待验证")
      4: 邀请已经过期(界面显示"已过期")
     */
    return {
      // autoVerify: false,
      selectAll: false,
      tab: 2,
      verifyList: [],
      selectedList: []
    }
  },
  props: ['params','autoVerify'],
  mounted() {


    for(let i = 0; i < 20; i++) {
      this.verifyList.push({
          wxid: Math.random().toString(16).slice(2),
          avatar: '',
          name: `用户A${i}`,
          gender: 0,
          time: '2019.2.11 20:11',
          type: i > 15 ? 'accepted' : i > 10 ? 'expired' : 'refer',
          service: {
            wxid: Math.random().toString(16).slice(2),
            name: '客服一号',
            friend_count: 3422,
            avatar: ''
          }
      })
    }
  },
  computed: {
    ...mapState(['manager']),
    matchedList() {
      return this.verifyList.filter(item=>item.type==this.tab)
    }
  },
  components: {
    UserListItem,
    ServiceListItem
  },
  methods: {
    getRecommendVal() {
      // if(!this.params.services)return;
      const service = this.params.services[0]
      console.log(this.manager.id)
      this.$api.validation.get({
        csId: this.manager.id,
        wxAccount: service.wxid
      }).then(data=>{
        // this.autoVerify = data.autopass
        this.$emit('getSetting',data)
      }).catch(e=>this.$msg(e))
    },
    transUser(item,service){
      const user = {
          wxid: item.wxid,
          avatar: item.avatar,
          csid:item.csid,
          name: item.nick,
          gender: item.sex === 1?1:0,
          time: this.formatTime(item.updateTime||item.createTime),
          type: item.status,
          wxaccount:item.wxaccount,
          service
      }
      return user
    },
    getValidationList() {
      let _verifyList = []
      const promises = this.params.services.map(s=>{
        return this.$api.validation.list({
          csId: this.manager.id,
          wxAccount: s.wxid
        }).then(data=>{
          return data.map(item=>this.transUser(item,s))
        })
      })
      Promise.all(promises).then(rs=>{
        rs.forEach(arr=>{
          _verifyList = _verifyList.concat(arr)
        })
        this.verifyList = _verifyList
        console.log('_verifyList',_verifyList)
      }).catch(e=>this.$msg(e))
    },
    toggleAutoVerify(e) {
      this.autoVerify = e.target.checked;
    },
    toggleSelectAll(e) {
      this.selectAll = e.target.checked;
      if (e.target.checked) {
        this.selectedList = this.matchedList
      } else {
        this.selectedList = []
      }
    },
    changeTab(type) {
      this.tab = type
    },
    toggleUserSelect(user, e) {
      if (e.target.checked) {
        this.selectedList.push(user)
      } else {
        this.selectedList = this.selectedList.filter(item=>item.wxid!=user.wxid)
      }
    },
    acceptRequest() {
      let list = {}
      let csid
      this.selectedList.forEach(user=>{
        const {wxaccount} = user
        csid = user.csid
        if(list[wxaccount]){
          list[wxaccount].push(user)
        }else{
          list[wxaccount] = []
          list[wxaccount].push(user)
        }
      })
      Object.keys(list).forEach(key=>{
        const arr = list[key]
        const friendAccountList = []
        // const {  } =
        arr.forEach(item=>{
          friendAccountList.push(item.wxid)
        })
        this.$api.validation.insert({
          csId:csid,
          wxAccount:key,
          friendAccountList
        }).then(data=>{
          this.$msg('设置成功')

        }).catch(e=>this.$msg(e))
      })

    },
    syncVerify(){
      (this.params.services||[]).forEach(account=>{
        this.$api.validation.sync({ wxAccount:account.wxid })
      })
      this.$message({
        type:'info',
        message:'正在同步，请稍后从新打开页面'
      })

    }
  },
  watch: {
    'params.services': function(val) {
      if(val && val[0]){
        this.getRecommendVal()
        this.getValidationList()
      }

    }
  }
}
</script>

<style scoped>
.list-item-avatar{
  width: 40px;
  height: 40px;
  margin-right: 4px;
}
.list-item-avatar img{
    width: 100%;
    border-radius: 3px;
}
.list-item-info{
  flex-grow: 1;
  justify-content: space-between;
  min-width: 0;
}
.list-item-name{
  font-size: 14px;
  padding-right: 20px;
  background-size: 15px 15px;
  background-position: center right;
  background-repeat: no-repeat;
  width: fit-content;
  margin-bottom: 6px;
}
.list-item-bottom-info {
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    font-size: 12px;
    color: #999;
}
.list-label{
  width: 150px
}
.attachInfoContainer{
  width: 600px;
}
</style>
